{extend name="common/base"/}
<!-- 主体 -->
{block name="body"}
<style type="text/css">
	/* 拖拽时显示移动光标 */
.layui-layer-gougu-admin .layui-layer-content {
    cursor: move;
}

/* 拖拽过程阴影效果 */
.layui-layer-moving {
    box-shadow: 0 0 20px rgba(0,0,0,0.2);
}
.layui-layer-gougu-admin {
    transform: translateZ(0);
}
</style>
<div class="p-3">
	<form class="layui-form gg-form-bar border-t border-x">
		<!-- <div class="layui-input-inline" style="width:300px;">
			<input type="text" name="keywords" placeholder="请输入关键字" class="layui-input" autocomplete="off" />
		</div> -->
		<div class="layui-input-inline" style="width:200px;">
			<select name="region" id="region" lay-reqText="请选择县区" lay-search=""  lay-filter="region">
					<option value="">--选择县区-- </option>
					{volist name=":get_region()" id="v"}
					<option value="{$v.id}">{$v.nianji} </option>
					{/volist}
				</select>
		</div>
		<div class="layui-input-inline" style="width:200px;">
			<input type="text" name="name" placeholder="商品名" class="layui-input" autocomplete="off" />
		</div>
		<div class="layui-input-inline" style="width:200px;">
			<input type="text" name="order_no" placeholder="订单号" class="layui-input" autocomplete="off" />
		</div>
		<div class="layui-input-inline" style="margin-left:20px;width:150px;">
			<input type="text" name="delivery_time1"   id="delivery_time1" autocomplete="off" placeholder="配送时间-开始" class="layui-input">
		</div>
		<div class="layui-input-inline" style="margin-left:20px">—</div>
		<div class="layui-input-inline" style="margin-left:20px;width:150px;">
			<input type="text" name="delivery_time2"   id="delivery_time2" autocomplete="off" placeholder="配送时间-结束" class="layui-input">
		</div>
		<div class="layui-input-inline">
		<button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="searchform">提交搜索</button>
		</div>
	</form>
	<table class="layui-hide" id="order" lay-filter="order"></table>
</div>

<script type="text/html" id="toolbarDemo">
	<div class="layui-btn-container">
		
		<span class="layui-btn layui-btn-sm" lay-event="add" data-title="添加订单表">+ 添加单条</span>
		<button class="layui-btn layui-btn-sm" lay-event="import" >批量导入</button>
	</div>
</script>

<script type="text/html" id="barDemo">
<div class="layui-btn-group">
	<!-- <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="read">查看</a> -->
	<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="dayin">热敏打印</a>
	<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="dayin2">打印</a>
	<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</div>
</script>

{/block}
<!-- /主体 -->

<!-- 脚本 -->
{block name="script"}
<script>
	const moduleInit = ['tool'];
	
	if ('ontouchstart' in window) {
    obj.find('.layui-layer-content').on('touchmove', function(e) {
        e.preventDefault();
    });
}	
	function gouguInit() {
		var table = layui.table,tool = layui.tool, form = layui.form;
		//日期选择
		layui.laydate.render({
			elem: '#delivery_time1' //指定元素
		});
		//日期选择
		layui.laydate.render({
			elem: '#delivery_time2' //指定元素
		});
		layui.pageTable = table.render({
			elem: '#order',
			title: '订单表列表',
			toolbar: '#toolbarDemo', 
			url: '/admin/order/datalist',
			defaultToolbar: [],
			page: true,
			limit: 15,
			cellMinWidth: 80,
			/*cellMinWidth: 80,done: function(res) {
			    // 覆盖打印按钮行为
			    $('.layui-table-tool .layui-icon-print').parent().on('click', function() {
			      customizePrint(res.data); // 调用自定义打印方法
			      return false; // 阻止默认打印
			    });
		  	},*/
		  	/*done: function(res) {
			    // 覆盖打印按钮行为
			    $('.layui-table-tool .layui-icon-print').parent().on('click', function() {
			    	
			      printCustomColumns(res.data); // 调用自定义打印方法
			      return false; // 阻止默认打印
			    });
		  	},*/
		  	done: function(res) {
			  // 覆盖打印按钮行为
			  //$('.layui-table-tool .layui-btn[lay-event="LAYTABLE_PRINT"]').on('click', function() {
			  $('.layui-table-tool .layui-icon-print').parent().on('click', function() {
			    printCustomColumns(res.data); // 调用自定义打印方法
			    return false; // 阻止默认行为
			  });
			},
			cols: [
				[
				/*{type: 'checkbox', fixed: 'left',
					printable: false},*/
				{
					fixed: 'left',
					field: 'id',
					title: '编号',
					align: 'center',
					width: 50,
					printable: false
				},{
					field: 'nianji',
					title: '县区',
					align: 'center',
					printable: true
				},{
					field: 'name',
					title: '商品名称',
					align: 'center',
					width: 130,
					printable: true
				},{
					field: 'specification',
					title: '规格',
					align: 'center',
					width: 130,
					printable: true
				},{
					field: 'purchaser',
					title: '采购方',
					align: 'center',
					width: 180,
					printable: true
				},{
					field: 'status',
					title: '状态',
					align: 'center',
					printable: false
				},{
					field: 'produced_time',
					title: '生产日期',
					align: 'center',
					width: 100,
					printable: true
				},{
					field: 'delivery_time',
					title: '配送日期',
					align: 'center',
					width: 100,
					printable: true
				},{
					field: 'sorting',
					title: '分拣量',
					align: 'center',
					printable: false,
					printable: true
				},{
					field: 'remark',
					title: '备注',
					align: 'center',
					printable: true
				},{
					field: 'order_no',
					title: '订单号',
					align: 'center',
					width: 130,
					printable: true
				},{
					field: 'sorting_admin',
					title: '分拣员',
					align: 'center'
				},{
					field: 'delivery_admin',
					title: '配送人',
					align: 'center',
					printable: true
				},{
					field: 'username',
					title: '创建人',
					align: 'center',
					printable: false
				},
				{
					fixed: 'right',
					field: 'right',
					title: '操作',
					toolbar: '#barDemo',
					width: 180,
					align: 'center',
					printable: false
				}				
				]
			]
		});
		
		//监听表头工具栏事件
		table.on('toolbar(order)', function(obj){
			if (obj.event === 'add') {
				tool.side("/admin/order/add");
				return false;
			}
			if (obj.event === 'import') {
				tool.side("/admin/order/order_import");
				return false;
			}
			if (obj.event === 'dayin') {

				//printCustomColumns('111'); // 调用自定义打印方法
			    return false; // 阻止默认行为
			}
		});

		//监听表格行工具事件
		table.on('tool(order)', function(obj) {
			var data = obj.data;
			if (obj.event === 'read') {
				tool.side('/admin/order/read?id='+obj.data.id);
			}
			else if (obj.event === 'dayin') {
				printremin(data); 	
			}else if (obj.event === 'dayin2') {
				print2(data); 	
			}else if (obj.event === 'edit') {
				tool.side('/admin/order/edit?id='+obj.data.id);
			}
			else if (obj.event === 'del') {
				layer.confirm('确定要删除该记录吗?', {
					icon: 3,
					title: '提示'
				}, function(index) {
					let callback = function (e) {
						layer.msg(e.msg);
						if (e.code == 0) {
							obj.del();
						}
					}
					tool.delete("/admin/order/del", { id: data.id }, callback);
					layer.close(index);
				});
			}
			return false;
		});

		//监听搜索提交
		form.on('submit(searchform)', function(data) {
			console.log(data);
			layui.pageTable.reload({
				where: {
					name: data.field.name,
					region: data.field.region,
					order_no: data.field.order_no,
					delivery_time1: data.field.delivery_time1,
					delivery_time2: data.field.delivery_time2
				},
				page: {
					curr: 1
				}
			});
			return false;
		});
		// 自定义打印函数
function printremin(data) {
	console.log(data);
	/*alert(data);
	return false;*/
  /*if (!data.length) {
    return layer.tips("当前表格无数据", this, { tips: 3 });
  }*/

  const printWindow = window.open("about:blank", "_blank");
  let tableContent = '<div class="custom-print-title" style="text-align:center;font-size:40px;margin-bottom:50px">山东汉达供应链管理有限公司销货单</div><table>';
  tableContent+='<tr><td class="tr-td-left">【订货单位】</td><td>'+data.purchaser+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">【食品名称】</td><td>'+data.name+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">【净含量】</td><td>'+data.sorting+'斤</td></tr>'
  tableContent+='<tr><td class="tr-td-left">【配送时间】</td><td>'+data.delivery_time+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">【备注】</td><td>'+data.remark+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">【温馨提示】</td><td>此单为配送业务出厂凭证，当日有效，过期作废。</td></tr></table>'
  const styles = `
    <style>
      body { font-size: 12px; color: #5F5F5F; }
      table { width: 100%; border-collapse: collapse; }
      th, td { 
        line-height: 40px; 
        padding: 9px 15px; 
        border: 0px solid #ccc; 
        text-align: left; 
        font-size: 30px; 


      }
      .tr-td-left{
      	width:35%;
      }
      .layui-hide { display: none; }
    </style>
  `;

  // 过滤掉不可打印的列
  const printableCols = layui.pageTable.config.cols[0].filter(col => col.printable !== false);
  /*
  // 生成表头
  let tableContent = '<div class="custom-print-title" style="text-align:center;font-size:30px;margin-bottom:50px">山东汉达供应链管理有限公司销货单</div><table>';
  tableContent += '<thead><tr>';
  printableCols.forEach(col => {
    tableContent += `<th>${col.title}</th>`;
  });
  tableContent += '</tr></thead>';

  // 生成表格数据
  tableContent += '<tbody>';
  data.forEach(item => {
    tableContent += '<tr>';
    printableCols.forEach(col => {
      tableContent += `<td>${item[col.field]}</td>`;
    });
    //tableContent += '<tr><td><td></tr>'
    tableContent += '</tr>';
  });
  tableContent += '</tbody></table>';*/

  printWindow.document.write(styles + tableContent);
  printWindow.document.close();

  // 处理浏览器兼容性
  if (layui.device("edg").edg) {
    printWindow.onafterprint = printWindow.close;
    printWindow.print();
  } else {
    printWindow.print();
    printWindow.close();
  }
}
function print2(data) {
  /*if (!data.length) {
    return layer.tips("当前表格无数据", this, { tips: 3 });
  }*/

  const printWindow = window.open("about:blank", "_blank");
  const styles = `
    <style>
      body { font-size: 12px; color: #5F5F5F; }
      table { width: 100%; border-collapse: collapse; }
      th, td { 
        line-height: 20px; 
        padding: 9px 15px; 
        border: 1px solid #ccc; 
        text-align: left; 
        font-size: 12px; 
      }
      .layui-hide { display: none; }
    </style>
  `;

  // 过滤掉不可打印的列
  const printableCols = layui.pageTable.config.cols[0].filter(col => col.printable !== false);
  
  // 生成表头
  let tableContent = '<div class="custom-print-title" style="text-align:center;font-size:30px;margin-bottom:50px">山东汉达供应链管理有限公司销货单</div><table>';
  tableContent+='<tr><td class="tr-td-left">收货单位</td><td>'+data.purchaser+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">配送日期</td><td>'+data.delivery_time+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">收货人</td><td>'+data.user+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">收货人电话</td><td>'+data.phone+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">收货人地址</td><td>'+data.address+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">备注</td><td>'+data.remark+'</td></tr>'
  tableContent+='<tr><td colspan="2"></td></tr>'


  tableContent+='<tr><td class="tr-td-left">食品名称</td><td>'+data.name+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">规格</td><td>'+data.name+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">生产日期</td><td>'+data.produced_time+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">分拣量</td><td>'+data.sorting+'斤</td></tr>'
  tableContent+='<tr><td class="tr-td-left">分拣员</td><td>'+data.sorting_admin+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">配送员</td><td>'+data.delivery_admin+'</td></tr></table>'
  /*tableContent += '<thead><tr>';
  printableCols.forEach(col => {
    tableContent += `<th>${col.title}</th>`;
  });
  tableContent += '</tr></thead>';

  // 生成表格数据
  tableContent += '<tbody>';
  data.forEach(item => {
    tableContent += '<tr>';
    printableCols.forEach(col => {
      tableContent += `<td>${item[col.field]}</td>`;
    });
    //tableContent += '<tr><td><td></tr>'
    tableContent += '</tr>';
  });
  tableContent += '</tbody></table>';*/


  printWindow.document.write(styles + tableContent);
  printWindow.document.close();

  // 处理浏览器兼容性
  if (layui.device("edg").edg) {
    printWindow.onafterprint = printWindow.close;
    printWindow.print();
  } else {
    printWindow.print();
    printWindow.close();
  }
}
function print2bak(data) {
  /*if (!data.length) {
    return layer.tips("当前表格无数据", this, { tips: 3 });
  }*/

  const printWindow = window.open("about:blank", "_blank");
  const styles = `
    <style>
      body { font-size: 12px; color: #5F5F5F; }
      table { width: 100%; border-collapse: collapse; }
      th, td { 
        line-height: 20px; 
        padding: 9px 15px; 
        border: 1px solid #ccc; 
        text-align: left; 
        font-size: 12px; 
      }
      .layui-hide { display: none; }
    </style>
  `;

  // 过滤掉不可打印的列
  const printableCols = layui.pageTable.config.cols[0].filter(col => col.printable !== false);
  
  // 生成表头
  let tableContent = '<div class="custom-print-title" style="text-align:center;font-size:30px;margin-bottom:50px">山东汉达供应链管理有限公司销货单</div><table>';
  /*tableContent += '<thead><tr>';
  printableCols.forEach(col => {
    tableContent += `<th>${col.title}</th>`;
  });
  tableContent += '</tr></thead>';

  // 生成表格数据
  tableContent += '<tbody>';
  data.forEach(item => {
    tableContent += '<tr>';
    printableCols.forEach(col => {
      tableContent += `<td>${item[col.field]}</td>`;
    });
    //tableContent += '<tr><td><td></tr>'
    tableContent += '</tr>';
  });
  tableContent += '</tbody></table>';*/


  printWindow.document.write(styles + tableContent);
  printWindow.document.close();

  // 处理浏览器兼容性
  if (layui.device("edg").edg) {
    printWindow.onafterprint = printWindow.close;
    printWindow.print();
  } else {
    printWindow.print();
    printWindow.close();
  }
}
		function printCustomColumns2(data) {
		  // ✅ 安全获取列配置（优先缓存，次优初始化参数）
		  const cacheCols = layui.table.cache.order?.[0]?.columns || [];
		  const initCols = layui.table.config.order?.init?.cols?.[0] || [];
		  const cols = cacheCols.length ? cacheCols : initCols;
		  //const cols = layui.table.config.order?.init?.cols?.[0] || [];

		  // ✅ 打印字段定义
		  const printFields = [ 'id','nianji', 'name', 'specification', 'delivery_time'];
		  const titleMap = {
		  	  id:'编号',
			  nianji: '县区',
			  name: '商品名称',
			  specification: '规格',
			  delivery_time: '配送时间'
			};
		  /*const headers = printFields.map(field => {
		    const col = cols.find(c => c.field === field);
		    return `<th>${col?.title || field}</th>`; // 自动适配中文标题
		  }).join('');*/
		  // ✅ 生成表头
		  /*const headers = printFields.map(field => {
		  const colConfig = cols.find(c => c.field === field);
		  return `<th width="${colConfig?.width || 100}">${titleMap[field] || field}</th>`;
			}).join('');*/
		  const headers = printFields.map(title => {
		    const colConfig = cols.find(c => c.title === title);
		    return `<th width="${colConfig?.width || 100}">${colConfig?.title  || title}</th>`;
		  }).join('');
		  /*const headers = printFields.map(field => {
		    const colConfig = cols.find(c => c.field === field);
		    return `<th width="${colConfig?.width || 100}">${colConfig?.title || field}</th>`;
		  }).join('');*/

		  // ✅ 构建数据行（兼容空数据）
		  const rows = (data || []).map(item => `
		    <tr>
		      ${printFields.map(field => `<td>${item[field] || ''}</td>`).join('')}
		    </tr>
		  `).join('');

		  // ✅ 生成打印内容
		  const printHtml = `
		    <style>
		    	 @media print {
		        @page { margin: 0; }
		        body { margin: 2cm; }
		        .print-title { font-size: 24px; text-align: center; margin-bottom: 20px; }
		        .layui-table { width: 100%; border-collapse: collapse; }
		        .layui-table th, 
		        .layui-table td { 
		          border: 1px solid #666; 
		          padding: 8px;
		          text-align: center;
		          font-size: 14px;
		        }
		      }
		    </style>
		    <div class="custom-print-title" style="text-align:center;font-size:30px;margin-bottom:50px">山东汉达供应链管理有限公司销货单</div>
		    <table class="layui-table>
		      <tbody><tr>${headers}</tr></tbody>
		      <tbody>${rows}</tbody>
		    </table>
		  `;
		  /*const printHtml = `
		    <style></style>
		    <div class="custom-print-title">订单表打印报表</div>
		    <table class="layui-table custom-print-table">
		      <thead><tr>${headers}</tr></thead>
		      <tbody>${rows}</tbody>
		    </table>
		  `;*/
		  // ✅ 安全打印
		  const printWindow = window.open('', '_blank');
		  if (printWindow) {
		    printWindow.document.write(printHtml);
		    printWindow.document.close();
		    printWindow.print();
		    printWindow.close();
		  } else {
		    layer.msg('浏览器阻止了弹窗，请允许后重试', {icon: 2});
		  }
		}

	}
</script>
{/block}
<!-- /脚本 -->